package greate.project;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Predicate;
import org.apache.camel.builder.PredicateClause;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

import java.util.Objects;

public class App {

    public static void main(String[] args) throws Exception {

        // 创建默认上下文
        CamelContext context = new DefaultCamelContext();

        // 现开启想表达的是 ， camel 在开启后可以动态的新增和关闭路由。
        context.start();

        // 新增路由
        context.addRoutes(new HelloWorldRoute01());
        context.addRoutes(new HelloWorldRoute02());

        Thread.sleep(3000);

        // 关闭 路由任务
        context.getRouteController().stopRoute("d");

        // 从上下文中删除路由
        context.removeRoute("d1");
        // 从上下文中删除路由
        context.removeRoute("d2");

        synchronized (App.class){
            App.class.wait();
        }

    }

    /**
     *  路由传递信息
     */
    static class HelloWorldRoute01 extends RouteBuilder {
        @Override
        public void configure() throws Exception {

            from("timer:foo?repeatCount=10")
                    .setBody(constant("12312313123123123"))
                    .process(exchange -> {
                        exchange.setProperty("ffff", new Thread("123"));
                        exchange.getMessage().setHeader("ddd" , "123");
                    })
                    .log("${body}")
                    .id("d1")
                    .choice()
                    .when(e->{
                        final Object body = e.getMessage().getBody();
                        if (body==null) {
                            return false;
                        }
                        if (body instanceof String) {
                            return !"".equals(((String) body).trim());
                        }
                        return true;
                    })
            .to("direct:hello02")
                    .process(exchange -> {
                        System.out.println(exchange.getPattern());
                        System.out.println(header("ddd").toString());
                    })
                    .otherwise()
                    .log("内容空白不向下传递")
            .endChoice();

        }
    }

    /**
     *  接受路由信息
     */
    static class HelloWorldRoute02 extends RouteBuilder {
        @Override
        public void configure() throws Exception {

            from("direct:hello02")
                    .log("loading... 02")
                    .process(exchange -> {
                        System.out.println(exchange.getPattern());
                        System.out.println(exchange.getProperty("ffff" , Thread.class).getName());
                    })
                    .id("d2");

        }
    }


}
